//
//  AddUserVC.m
//  UHealth
//
//  Created by gjtxz on 15/2/5.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "AddUserVC.h"
#import "iToast.h"
#import "UUDatePicker.h"
#import "UserObj.h"

#import "NavView.h"
#import "iToast.h"
#import "AFNetworking.h"
#import "NSString+BloodSugar.h"
#import "DBManage.h"
#import "MBProgressHUD+YCL.h"

#import "UIImageView+WebCache.h"

#import "VPImageCropperViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>

#define ORIGINAL_MAX_WIDTH 640.0f
#define kFieldJX    35.f

@interface AddUserVC ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate, VPImageCropperDelegate,UIPickerViewDataSource,UIPickerViewDelegate>


@property (nonatomic,strong) UIImageView            *portraitImageView;//头像
@property (nonatomic,strong) UITextField            *fieldName;//名字
@property (nonatomic,strong) UIButton               *maleBtn;
@property (nonatomic,strong) UIButton               *femaleBtn;
@property (nonatomic,strong) UITextField            *fieldBirth;//出生年月
@property (nonatomic,strong) UITextField            *fieldHeight;//身高
@property (nonatomic,strong) UITextField            *fieldWeight;//体重

@property (nonatomic,strong) UserObj                *user;

@property (nonatomic,strong) UIPickerView           *hPick;
@property (nonatomic,strong) UIPickerView           *wPick;

@property (nonatomic,strong) UIImage                *myImg;
@end

@implementation AddUserVC

-(id)initWithUser:(UserObj*)user
{
    _user = user;
    self = [super init];
    if (self) {
        self.view.backgroundColor = kBacColor;
    }
    return self;
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [MobClick beginLogPageView:kLocal(@"addUser")];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    [MobClick endLogPageView:kLocal(@"addUser")];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NavView *nav = [[NavView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, kNavHeight) andTitleStr:kLocal(@"addUser") andVC:self];
    [self.view addSubview:nav];
    
    UIButton *enterBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    enterBtn.frame = CGRectMake(WIDTH - 55, 21, 40, 40);
    [enterBtn setTitle:kLocal(@"save_btn") forState:UIControlStateNormal];
    [enterBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [enterBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    enterBtn.tag = 3;
    [nav addSubview:enterBtn];
    
    UILabel *hit1 = [[UILabel alloc]initWithFrame:CGRectMake(20, 5 +kNavHeight, WIDTH-40, 20)];
    hit1.text = kLocal(@"hit1");
    hit1.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:hit1];
    
    self.portraitImageView.image = [UIImage imageNamed:@"user"];
    [self.view addSubview:self.portraitImageView];
    
    UUDatePicker *datePicker
    = [[UUDatePicker alloc]initWithframe:CGRectMake(0, 0, WIDTH, 200)
                             PickerStyle:UUDateStyle_YearMonthDay
                             didSelected:^(NSString *year,
                                           NSString *month,
                                           NSString *day,
                                           NSString *hour,
                                           NSString *minute,
                                           NSString *weekDay) {
                                 _fieldBirth.text = [NSString stringWithFormat:@"%@-%@-%@",year,month,day];
                                 
                             }];
    datePicker.backgroundColor = kBacColor;
    datePicker.ScrollToDate = [NSDate dateFromString:@"1970-01-01" withFormat:@"YYYY-MM-dd"];
   
    _hPick = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    _hPick.delegate = self;
    _hPick.dataSource = self;
    _hPick.backgroundColor = kBacColor;
    [_hPick selectRow:75 inComponent:0 animated:NO];
    
    _wPick = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    _wPick.delegate = self;
    _wPick.dataSource = self;
    _wPick.backgroundColor = kBacColor;
    [_wPick selectRow:40 inComponent:0 animated:NO];
    
    NSArray *imgArr = @[@"relation",@"sex",@"age",@"height",@"weight"];
    _fieldName = [[UITextField alloc]init];
    _fieldBirth = [[UITextField alloc]init];
    _fieldHeight = [[UITextField alloc]init];
    _fieldWeight = [[UITextField alloc]init];
    NSArray *fArr = @[_fieldName,[[UITextField alloc]init],_fieldBirth,_fieldHeight,_fieldWeight];
    NSArray *plaArr = @[kLocal(@"editHit1"),@"",kLocal(@"editHit2"),kLocal(@"editHit3"),kLocal(@"editHit4")];
    for (int i = 0; i < 5; i++) {
        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(20, kNavHeight+120+i*kFieldJX, kFieldJX, kFieldJX)];
        img.image = [UIImage imageNamed:imgArr[i]];
        [self.view addSubview:img];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(20, kNavHeight+155+ i*kFieldJX, WIDTH - 40, 0.5)];
        lineView.backgroundColor = [UIColor grayColor];
        [self.view addSubview:lineView];
        if (i == 1) {
            continue;
        }
        UITextField *field = fArr[i];
        field.frame = CGRectMake(70, kNavHeight+120 + i*kFieldJX, WIDTH-90, 40);
        field.font = [UIFont systemFontOfSize:14.0];
        field.placeholder = plaArr[i];
        field.clearButtonMode = UITextFieldViewModeWhileEditing;
        if (i == 2) {
            field.inputView = datePicker;
        }
        if (i == 3) {
            field.inputView = _hPick;
        }
        if (i == 4) {
            field.inputView = _wPick;
        }
        [self.view addSubview:field];
    }
    
    _maleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _maleBtn.frame = CGRectMake(70, kNavHeight+120 + kFieldJX, 50, 40);
    [_maleBtn setImage:[UIImage imageNamed:@"male"] forState:UIControlStateNormal];
    [_maleBtn setTitle:kLocal(@"male") forState:UIControlStateNormal];
    [_maleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _maleBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [_maleBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    _maleBtn.tag = 5;
    [self.view addSubview:_maleBtn];
    
    _femaleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _femaleBtn.frame = CGRectMake(120, kNavHeight+120 + kFieldJX, 50, 40);
    [_femaleBtn setImage:[UIImage imageNamed:@"female_line"] forState:UIControlStateNormal];
    [_femaleBtn setTitle:kLocal(@"female") forState:UIControlStateNormal];
    [_femaleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _femaleBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [_femaleBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    _femaleBtn.tag = 6;
    [self.view addSubview:_femaleBtn];
    
    
    if (!_user) {
        _user = [[UserObj alloc]init];
        _user.userID = kNetID;
        _user.famID = 0;
        _user.headImg = @"";
        _portraitImageView.image = [UIImage imageNamed:@"user"];
    }else{
        [_portraitImageView sd_setImageWithURL:[NSURL URLWithString:_user.headImg] placeholderImage:[UIImage imageNamed:@"user"]];

        _fieldName.text = _user.name;
        if (_user.sex) {
            [_maleBtn setImage:[UIImage imageNamed:@"male_line"] forState:UIControlStateNormal];
            [_femaleBtn setImage:[UIImage imageNamed:@"male"] forState:UIControlStateNormal];
        }
        _fieldBirth.text = _user.birthDate;
        _fieldHeight.text = [NSString stringWithFormat:@"%03d cm",(int)_user.height];
        _fieldWeight.text = [NSString stringWithFormat:@"%03d kg",(int)_user.weight];
        
        datePicker.ScrollToDate = [NSDate dateFromString:_user.birthDate withFormat:@"YYYY-MM-dd"];
        if ((int)_user.height >= 100) {
            [_hPick selectRow:(int)_user.height - 100 inComponent:0 animated:NO];
        }
        if ((int)_user.weight >= 30) {
            [_wPick selectRow:(int)_user.weight - 30 inComponent:0 animated:NO];
        }
        /********/
        //暂时取消删除
        UIButton *deletBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        if (VIEW_3_5_INCH) {
            deletBtn.frame = CGRectMake(40, HEIGHT - 30 - 40, WIDTH - 80, 40);
        }else{
            deletBtn.frame = CGRectMake(40, HEIGHT - 50 - 40, WIDTH - 80, 40);
        }
        [deletBtn setTitle:kLocal(@"delete") forState:UIControlStateNormal];
        [deletBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [deletBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
        deletBtn.tag = 4;
        [deletBtn.layer setMasksToBounds:YES];
        [deletBtn.layer setCornerRadius:1.0];//设置矩形是个圆角半径
        deletBtn.backgroundColor = kBlueColor;
//        [self.view addSubview:deletBtn];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)BtnClick:(UIButton *)btn
{
    NSString *name = _fieldName.text;
    NSString *birthDate = _fieldBirth.text;
    NSString *height = _fieldHeight.text;
    NSString *weight = _fieldWeight.text;
    
    if ((!name.length || !birthDate.length || !height.length || !weight.length) && btn.tag < 4 ) {
        [[iToast makeText:kLocal(@"infoHit")] show];
        return;
    }
    [self.view endEditing:YES];
    switch (btn.tag) {

        case 3:{//添加或者更新
            _user.name = name;
            _user.birthDate = birthDate;
            _user.height = [[height substringToIndex:3] floatValue];
            _user.weight = [[weight substringToIndex:3] floatValue];
            [self addOrUpdateFamUserInfo];
        }
            break;
        case 4://删除用户 暂时取消
        {
            NSString *conStr = [NSString stringWithFormat:@"%@ = '%ld' and %@ = '%d'",kUserId,kNetID,kFamID,_user.famID];
            [[DBManage sharedManager] deleteDataFromTable:kUserTable andConditions:conStr];
            if (_block) {
                _block(_user.famID,YES);
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        case 5:
            _user.sex = 0;
            [_maleBtn setImage:[UIImage imageNamed:@"male"] forState:UIControlStateNormal];
            [_femaleBtn setImage:[UIImage imageNamed:@"female_line"] forState:UIControlStateNormal];
            break;
        case 6:
            _user.sex = 1;
            [_maleBtn setImage:[UIImage imageNamed:@"male_line"] forState:UIControlStateNormal];
            [_femaleBtn setImage:[UIImage imageNamed:@"female"] forState:UIControlStateNormal];
            break;
        default:
            break;
    }
}


-(void)addOrUpdateFamUserInfo
{
    if(!kNetID){
        [[iToast makeText:kLocal(@"notLogin")]show];
        return;
    }
    if (!kNetIsOK) {
        [[iToast makeText:kLocal(@"netNoOk")]show];
        return;
    }
    MBProgressHUD *HUD = [MBProgressHUD showWhileExecuting:@"更新资料中。。。"];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
    NSString *postStr = [NSString stringWithFormat:@"%@/action/json/login.jsp",kBaseUrl];
    NSDictionary *parameters = @{@"action": @"memberFamInfoEdit",
                                 @"userid":[NSString stringWithFormat:@"%ld",kNetID],
                                 @"famid":[NSString stringWithFormat:@"%d",_user.famID],
                                 @"mem_name":_user.name,
                                 @"mem_birth":_user.birthDate,
                                 @"mem_sex":[NSString stringWithFormat:@"%d",_user.sex],
                                 @"men_shengao":[NSString stringWithFormat:@"%d",(int)_user.height],
                                 @"men_tizhong":[NSString stringWithFormat:@"%d",(int)_user.weight],
                                 @"mem_province":@"0",
                                 @"mem_city":@"0",
                                 @"mem_area":@"0",
                                 @"filenum":[NSString stringWithFormat:@"%d",_myImg != nil],
                                 @"mem_mobile":@"",
                                 @"xt_standardvalue":@{@"timetype1":@"6.0",
                                                       @"timetype2":@"10.0",
                                                       @"timetype3":@"4.5",
                                                       @"timetype4":@"5.9",
                                                       @"timetype5":@"5.0",
                                                       @"timetype6":@"6.9",
                                                       @"timetype7":@"7.9"}};
    [manager POST:postStr parameters:parameters constructingBodyWithBlock:^(id formData){
        if (_myImg) {
            [formData appendPartWithFileData:UIImagePNGRepresentation(_myImg) name:@"img0" fileName:@"img0.png" mimeType:@"image/png"];
        }
    }  success:^(AFHTTPRequestOperation *operation, id responseObject) {
        kDebug(@"Success: %@ \n%@", operation.responseString, responseObject);
        /**
         {
             famid = 6;
             imgpath = "";
             msg = "提交成功";
             type = 1;
             userid = 22120271;
         }
         */
        BOOL type = [responseObject[@"type"] boolValue];
        if(type){
            _user.famID = [responseObject[@"famid"] intValue];//更新用户ID
            _user.headImg = responseObject[@"imgpath"];

            //添加或者更新
            [[DBManage sharedManager] insertData:_user andTable:kUserTable];

            // 传出用户对象，是否删除
            if (_block) {
                _block(_user.famID,NO);
            }
            [HUD hide:NO];
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
            [HUD hide:NO];
        }
        [[iToast makeText:[responseObject objectForKey:@"msg"]] show];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {//网络失败本地取
        kDebug(@"Error: %@", error);
        [HUD hide:NO];
        [[iToast makeText:kLocal(@"netError")]show];
    }];
    

}

#pragma mark - 选择器

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if ([_wPick isEqual:pickerView]) {
        return 100;
    }
    return 150;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if ([_wPick isEqual:pickerView]) {
        return [NSString stringWithFormat:@"%03d kg",30 + (int)row];
    }
    return  [NSString stringWithFormat:@"%03d cm",100 + (int)row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if ([_wPick isEqual:pickerView]) {
        _fieldWeight.text = [NSString stringWithFormat:@"%03d kg",30 + (int)row];
    }else{
        _fieldHeight.text = [NSString stringWithFormat:@"%03d cm",100 + (int)row];
    }
    
}


#pragma mark - 触摸

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark - headimg

#pragma mark portraitImageView getter
- (UIImageView *)portraitImageView {
    if (!_portraitImageView) {
        CGFloat w = 80.f; CGFloat h = w;
        CGFloat x = (WIDTH - w)/2;
        CGFloat y = 30+kNavHeight;
        _portraitImageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, w, h)];
        [_portraitImageView.layer setCornerRadius:(_portraitImageView.frame.size.height/2)];
        [_portraitImageView.layer setMasksToBounds:YES];
        [_portraitImageView setContentMode:UIViewContentModeScaleAspectFill];
        [_portraitImageView setClipsToBounds:YES];
        _portraitImageView.layer.shadowColor = kBlueColor.CGColor;
        _portraitImageView.layer.shadowOffset = CGSizeMake(4, 4);
        _portraitImageView.layer.shadowOpacity = 0.5;
        _portraitImageView.layer.shadowRadius = 2.0;
        _portraitImageView.layer.borderColor = [kBlueColor CGColor];
        _portraitImageView.layer.borderWidth = 1.0f;
        _portraitImageView.userInteractionEnabled = YES;
        _portraitImageView.backgroundColor = [UIColor clearColor];
        UITapGestureRecognizer *portraitTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(editPortrait)];
        [_portraitImageView addGestureRecognizer:portraitTap];
    }
    return _portraitImageView;
}

- (void)editPortrait {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}

#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    self.portraitImageView.image = editedImage;
    _myImg = editedImage;
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
    }];
//    [UIImagePNGRepresentation(editedImage) writeToFile: kPostImgFilePath atomically:YES];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([self isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                             }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                             }];
        }
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}


#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        kDebug(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
